import json
import time
import random

import requests
from client import Client
from fetcher import Fetcher
from main.util import debug, dict_to_obj, get_distance

from pojo.community import Community
from pojo.surrounding import Surrounding

client = None
table_communities = 'communities'
table_houses = 'houses'

search_list = ['地铁站', '公交站', '幼儿园', '小学', '中学', '大学', '医院', '商场', '超市', '市场', '餐厅', '电影院', '健身房']
# 从此ID继续
resume_cid = ''


def get_resume_hid_index(cid):
    table = client.get_collection(table_communities)
    result = [i["cid"] for i in table.find({}, {'cid': 1})]
    try:
        i_cid = result.index(cid)
    except ValueError:
        i_cid = 0
    return i_cid


def get_community_info_ext(comm: Community):
    hid = client.get_collection(table_houses).find_one({'cid': comm.cid})['hid']
    url = 'https://ts.lianjia.com/chengjiao'
    fetcher = Fetcher(url)
    html = fetcher.get_content4(f'resblock?hid={hid}&rid={comm.cid}')
    obj = json.loads(html)
    comm.build_time = obj['data']['resblock']['buildYear'].split('年')[0]
    comm.building_count = obj['data']['resblock']['buildNum'].split('栋')[0]
    comm.building_type = obj['data']['resblock']['buildType']


def get_surroundings(p, kw):
    lng = p[0]
    lat = p[1]
    param = {
        'query': kw,
        'location': f'{lat},{lng}',
        'ak': 'dASz7ubuSpHidP1oQWKuAK3q',
        'radius': 2000,
        'output': 'json'
    }
    res = requests.get('https://api.map.baidu.com/place/v2/search/', params=param)
    debug(res.url, '调用地图接口' + kw)
    s_list = []
    for line in res.json()['results']:
        s = Surrounding()
        s.srd_type = kw
        s.srd_name = line['name']
        s.srd_addr = line['address']
        s.latitude = line['location']['lat']
        s.longitude = line['location']['lng']
        s.srd_distance = round(get_distance((float(s.longitude), float(s.latitude)), p), 2)
        s_list.append(s.__dict__)

    print(s_list)
    return s_list


def get_community_ids():
    table = client.get_collection(table_communities)
    # 查找 有经纬度 但是没有详细信息的
    ids = [i["cid"] for i in table.find({'latitude':{'$ne':''},'build_time':''}, {'cid': 1})]
    return ids


def update_community(comm: Community):
    table = client.get_collection(table_communities)
    c_dict = comm.__dict__
    c_dict['surroundings'] = comm.surroundings
    print(c_dict)
    res = table.update_one({'cid': comm.cid}, {'$set': c_dict})
    if res.modified_count > 0:
        print("更新小区成功")


if __name__ == '__main__':

    """
        根据小区，获取小区详细信息
    """

    client = Client()
    cids = get_community_ids()
    cid_i = get_resume_hid_index(resume_cid)
    # 遍历小区列表
    t_comm = client.get_collection(table_communities)
    size = len(cids)-cid_i
    for i,c in enumerate(cids[cid_i:]):
        debug(c,f"进入小区 {i}/{size}")
        line = t_comm.find_one({'cid': c})
        comm = dict_to_obj(Community, line)

        # 有数据的的跳过
        if comm.build_time != '':
            continue

        # 查找小区信息
        get_community_info_ext(comm)
        # 查找配套
        surds = []
        for kw in search_list:
            surds.extend(get_surroundings((float(comm.longitude), float(comm.latitude)), kw))
            # time.sleep(0.1)
        comm.surroundings = surds
        # 更新community
        update_community(comm)
        time.sleep(random.randint(1, 3))
